package com.sumer.psychology.blog.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.blog.infrastructure.persistence.mongo.MongoBlogRepository;
import com.sumer.psychology.blog.infrastructure.persistence.mongo.MongoCategoryListRepository;
import com.sumer.psychology.blog.infrastructure.persistence.redis.RedisBlogRepository;
import com.sumer.psychology.common.notification.NotificationReader;
import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 博客创建监听
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/29
 * Time: 15:17
 */
public class BlogCreatedEventListener extends ExchangeListener {
    private static Logger logger = LoggerFactory.getLogger(BlogCreatedEventListener.class);

    private MongoBlogRepository mongoBlogRepository;
    private MongoCategoryListRepository mongoCategoryListRepository;
    private RedisBlogRepository redisBlogRepository;

    public BlogCreatedEventListener(MongoBlogRepository mongoBlogRepository,
                                    MongoCategoryListRepository mongoCategoryListRepository,
                                    RedisBlogRepository redisBlogRepository) {
        this.mongoBlogRepository = mongoBlogRepository;
        this.mongoCategoryListRepository = mongoCategoryListRepository;
        this.redisBlogRepository = redisBlogRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        logger.info("有一个blog被创建：{}", aTextMessage);

        mongoBlogRepository.add(aTextMessage);
        redisBlogRepository.add(aTextMessage);

        NotificationReader reader = new NotificationReader(aTextMessage);
        String categoryId = reader.eventStringValue("categoryId");
        if (StringUtils.isNotBlank(categoryId)) {
            mongoCategoryListRepository.increaseBlogSize(aTextMessage);
        }
    }

    @Override
    protected String[] listensTo() {
        return new String[]{"com.sumer.psychology.blog.domain.model.BlogCreatedEvent"};
    }
}
